<template>
    <div class="workflow-management">
        <div class="workflow-management__header">
            <h2>工作流管理</h2>
            <el-button type="primary" @click="handleCreateWorkflow">
                创建工作流
            </el-button>
        </div>

        <el-table
            v-loading="loading"
            :data="workflows"
            style="width: 100%"
        >
            <el-table-column prop="name" label="名称" />
            <el-table-column prop="description" label="描述" />
            <el-table-column prop="category" label="分类" />
            <el-table-column prop="author" label="作者" />
            <el-table-column label="预览图">
                <template #default="{ row }">
                    <el-image
                        style="width: 100px; height: 100px"
                        :src="row.thumbnail"
                        fit="cover"
                        :preview-src-list="[row.thumbnail]"
                    />
                </template>
            </el-table-column>
            <el-table-column label="标签">
                <template #default="{ row }">
                    <el-tag
                        v-for="tag in row.tags"
                        :key="tag"
                        size="small"
                        style="margin-right: 4px"
                    >
                        {{ tag }}
                    </el-tag>
                </template>
            </el-table-column>
            <el-table-column label="统计">
                <template #default="{ row }">
                    <div class="stats">
                        <span>使用: {{ row.stats?.uses || 0 }}</span>
                        <span>点赞: {{ row.stats?.likes || 0 }}</span>
                        <span>查看: {{ row.stats?.views || 0 }}</span>
                    </div>
                </template>
            </el-table-column>
            <el-table-column label="状态">
                <template #default="{ row }">
                    <el-tag :type="row.isPublic ? 'success' : 'info'">
                        {{ row.isPublic ? '已发布' : '未发布' }}
                    </el-tag>
                </template>
            </el-table-column>
            <el-table-column label="版本" prop="version" width="80" />
            <el-table-column label="操作" width="200">
                <template #default="{ row }">
                    <el-button-group>
                        <el-button size="small" @click="handleEditWorkflow(row)">
                            编辑
                        </el-button>
                        <el-button
                            size="small"
                            type="danger"
                            @click="handleDeleteWorkflow(row)"
                        >
                            删除
                        </el-button>
                    </el-button-group>
                </template>
            </el-table-column>
        </el-table>

        <el-dialog
            v-model="dialogVisible"
            :title="isEdit ? '编辑工作流' : '创建工作流'"
            width="60%"
            destroy-on-close
        >
            <workflow-form
                v-if="dialogVisible"
                :workflow="currentWorkflow"
                @submit="handleSubmitWorkflow"
                @cancel="dialogVisible = false"
            />
        </el-dialog>
    </div>
</template>

<script lang="ts" setup>
import { ref, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { workflowApi } from '@/api/workflow';
import WorkflowForm from '@/components/workflow/WorkflowForm.vue';
import type { WorkflowTemplate } from '@/types';
import { useRouter } from 'vue-router';

const workflows = ref<WorkflowTemplate[]>([]);
const loading = ref(false);
const dialogVisible = ref(false);
const isEdit = ref(false);
const currentWorkflow = ref<Partial<WorkflowTemplate> | null>(null);
const router = useRouter();

// 加载工作流列表
const loadWorkflows = async () => {
    try {
        loading.value = true;
        const { data } = await workflowApi.getAllWorkflows();
        workflows.value = data.data;  // 注意这里的嵌套 data
    } catch (error) {
        ElMessage.error('加载工作流失败');
        console.error('Load workflows error:', error);
    } finally {
        loading.value = false;
    }
};

// 处理创建工作流
const handleCreateWorkflow = () => {
    isEdit.value = false;
    currentWorkflow.value = null;
    dialogVisible.value = true;
    router.push('/workflow/create');
};

// 处理编辑工作流
const handleEditWorkflow = (workflow: WorkflowTemplate) => {
    isEdit.value = true;
    currentWorkflow.value = { ...workflow };
    dialogVisible.value = true;
    router.push(`/workflow/${workflow.id}/edit`);
};

// 处理删除工作流
const handleDeleteWorkflow = async (workflow: WorkflowTemplate) => {
    try {
        await ElMessageBox.confirm('确定要删除该工作流吗？', '提示', {
            type: 'warning'
        });
        const { data } = await workflowApi.deleteWorkflow(workflow.id);
        if (data.success) {
            ElMessage.success('删除成功');
            loadWorkflows();
        }
    } catch (error) {
        if (error !== 'cancel') {
            ElMessage.error('删除失败');
            console.error('Delete workflow error:', error);
        }
    }
};

// 处理提交工作流
const handleSubmitWorkflow = async (formData: Partial<WorkflowTemplate>) => {
    try {
        if (isEdit.value && currentWorkflow.value?.id) {
            const { data } = await workflowApi.updateWorkflow(
                currentWorkflow.value.id,
                formData
            );
            ElMessage.success('更新成功');
        } else {
            const { data } = await workflowApi.createWorkflow(formData);
            ElMessage.success('创建成功');
        }
        dialogVisible.value = false;
        loadWorkflows();
    } catch (error) {
        ElMessage.error(isEdit.value ? '更新失败' : '创建失败');
        console.error('Submit workflow error:', error);
    }
};

onMounted(() => {
    loadWorkflows();
});
</script>

<style lang="scss" scoped>
.workflow-management {
    padding: 20px;

    &__header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 20px;
    }

    .stats {
        display: flex;
        gap: 10px;
    }
}
</style> 